<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
</head>
<body>
<div>
    <input type="text" id="msg" placeholder="请输入消息"/>
    <button onclick="send()">发送</button>
    <div id="msg-list">
    </div>
    <button onclick="websocket.close()">断开连接</button>
    <button onclick="reconnect()">重新连接</button>
</div>
<script type="text/javascript">
    let websocket = new WebSocket("ws://localhost:8080/chat");

    // 连接断开
    websocket.onclose = e => {
        console.log(`连接关闭: code=${e.code}, reason=${e.reason}`)
    }
    // 收到消息
    websocket.onmessage = e => {
        console.log(`收到消息：${e.data}`);
    }
    // 异常
    websocket.onerror = e => {
        console.log("连接异常")
        console.error(e)
    }
    // 连接打开
    websocket.onopen = e => {
        console.log("连接打开");

        // 创建连接后，往服务器连续写入3条消息
        websocket.send("此信息由客户端发送");

        // 也可以由客户端主动断开
        // websocket.close();
    }
    function send() {
        let msg = document.getElementById("msg").value;
        if (msg) {
            websocket.send(msg);
        }
        document.getElementById("msg").value = "";
        document.getElementById("msg-list").innerHTML += `<div>${msg}</div>`;
    }
    function reconnect() {
        websocket.close();
        websocket = new WebSocket("ws://localhost:8080/chat");
    }
</script>
</body>
</html>
